package com.erp.framework.controller.taglib;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.jsp.JspException;

import com.erp.framework.model.dao.ServiceLocator;
import com.erp.framework.util.logger.Logger;

public class CustomDescDefTag extends javax.servlet.jsp.tagext.TagSupport {

	private String table = null;

	private String column = null;

	private String where = null;

	private String defValue = null;

	public void setTable(String text) {

		this.table = text;
	}

	public void setColumn(String text) {

		this.column = text;
	}

	public void setWhere(String text) {

		this.where = text;
	}

	public void setDefValue(String text) {

		this.defValue = text;
	}

	public int doEndTag() throws JspException {

		String rslt = "";
		Connection conn = null;
		PreparedStatement pStmt = null;
		ResultSet rs = null;
		String query = "";
		String preparedQuery = "";

		try {

			query = "SELECT " + column + " COLA FROM " + table + ((where != null && !where.equals("")) ? " WHERE " + where : "");
			// preparedQuery = SimpleString.escape(query, '\'');
			preparedQuery = query;

			conn = ServiceLocator.getInstance().getDSDBConnection();
			// stmt = conn.createStatement();
			pStmt = conn.prepareStatement(preparedQuery);
			Logger.all(this, "doEndTag(), sql=" + preparedQuery);
			// rs = stmt.executeQuery(query);
			rs = pStmt.executeQuery();

			if (rs != null && rs.next()) {
				rslt = (rs.getString(1) == null) ? "" : rs.getString(1).trim();
			}

			rslt = ((rslt == null) || ("".equals(rslt))) ? defValue : rslt;

			Logger.all(this, "doEndTag(), html=" + rslt.toString());
			pageContext.getOut().print(rslt);
		} catch (Exception e) {
			Logger.logExceptions(this, e);
			Logger.error("doEndTag(), html=" + rslt.toString());
			Logger.error("doEndTag(), sql=" + preparedQuery);
		} finally {
			try {
				if (rs != null)
					rs.close();
				if (pStmt != null)
					pStmt.close();
				if (conn != null)
					conn.close();
			} catch (Exception e) {
				Logger.logExceptions(this, e);
			}
		}

		return EVAL_PAGE;
	}
}
